// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'package:aircraft_war/bloc/game_state_cubit.dart';
import 'package:aircraft_war/commons/constants.dart';
import 'package:aircraft_war/components/enemy_aircraft.dart';
import 'package:aircraft_war/generated/assets.dart';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flame/flame.dart';

/// Created by changlei on 2022/5/16.
///
/// 子弹
class Bullet extends GameStatePositionComponent with CollisionCallbacks {
  /// 子弹
  Bullet({
    this.type = BulletType.normal,
    super.position,
    super.anchor,
    super.angle,
  })  : _sprite = Sprite(Flame.images.fromCache(type.path)),
        super(
          size: bulletSize,
        );

  /// 子弹类型
  final BulletType type;
  final Sprite _sprite;

  late double _speed = type.speed;

  /// 增加速度
  void growth(double offset) {
    _speed += offset;
  }

  @override
  Future<void> onLoad() async {
    await add(RectangleHitbox()..collisionType = CollisionType.passive);
  }

  @override
  void render(Canvas canvas) {
    _sprite.render(canvas);
  }

  @override
  void update(double dt) {
    if (gameRef.stateCubit.state != GameState.running) {
      return;
    }
    if (!containsOfParent(position) && !containsOfParent(position + size)) {
      removeFromParent();
      return;
    }
    position.y -= _speed * dt;
  }

  @override
  void onNewState(GameState state) {
    switch (state) {
      case GameState.idle:
      case GameState.pending:
      case GameState.stopped:
        removeFromParent();
        break;
      case GameState.pausing:
        break;
      case GameState.running:
        break;
    }
  }

  @override
  void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
    super.onCollision(intersectionPoints, other);
    if (other is! EnemyAircraft || !other.isActive || !gameRef.isRunning) {
      return;
    }
    removeFromParent();
  }
}

/// 子弹类型
enum BulletType {
  /// 普通子弹
  normal(Images.bullet1, 800.0),

  /// 增强子弹
  enhance(Images.bullet2, 1400.0);

  /// 子弹类型
  const BulletType(this.path, this.speed);

  /// 图片
  final String path;

  /// 速度
  final double speed;
}
